package com.cheche.dn.infrastructure.externalwebservice;

import com.cheche.dn.common.Filter;
import com.cheche.dn.common.base.Service;
import com.cheche.dn.domain.user.User;
import com.cheche.dn.infrastructure.security.ExternalServiceAuthenticator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 用户账号验证
 * Created by cheshun on 15/8/1.
 */
@Component("userServiceAuthenticator")
public class UserServiceAuthenticator implements ExternalServiceAuthenticator {

    @Autowired
    private Service service;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostConstruct
    protected void initialize() {
        if (!service.exists(User.class, Filter.eq(User.USERNAME_PROPERTY_NAME, "test0000"))) {
            User user = new User();
            user.setUsername("test0000");
            user.setPassword(passwordEncoder.encode("000000"));
            user.setNickname("测试0000");
            service.save(user);
        }
    }

    @Override
    public PreAuthenticatedAuthenticationToken authenticate(String username, String password) {

        User user = service.find(User.class, Filter.eq(User.USERNAME_PROPERTY_NAME, username));
        if (user != null) {
            if (passwordEncoder.matches(password, user.getPassword())) {
                return new PreAuthenticatedAuthenticationToken(user, null, null);
            } else {
                throw new BadCredentialsException("Password not verified");
            }
        }
        throw new UsernameNotFoundException("Username not found");
    }


}
